import Vue from 'vue'
import VueRouter from 'vue-router'
const home = () => import('../views/home/home.vue')
const goods = () => import('../views/goods/goods.vue')
const user = () => import('../views/users/user.vue')
const guanli = () => import('../views/guanli/guanli.vue')
const main1 = () => import('../views/main/main.vue')
const login = () => import('../views/login/login.vue')
const dingdan = () => import('../views/dingdan/dingdan.vue')
const system = () => import('../views/system/system.vue')

Vue.use(VueRouter)
const originalPush = VueRouter.prototype.push
// 修改 原型对象中的push方法
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}


const routes = [{
    path: '',
    redirect: '/login'
  },
  {
    path: '/login',
    component: login
  },
  {
    path: '/main',
    component: main1,
    children: [{
        path: '',
        redirect: '/home'
      },
      {
        name: '首页',
        path: '/home',
        component: home
      },
      {
        name: '用户管理',
        path: '/user',
        component: user
      },
      {
        name: '商品管理',
        path: '/goods',
        component: goods
      },
      {
        name: '用户密码管理',
        path: '/guanli',
        component: guanli
      }, {
        name: '订单管理',
        path: '/dingdan',
        component: dingdan
      }, {
        name: '系统参数',
        path: '/system',
        component: system
      }

    ]
  },



]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//挂载路由导航守卫,to表示将要访问的路径，from表示从哪里来，next是下一个要做的操作
router.beforeEach((to, from, next) => {
  if (to.path === '/login')
    return next();

  //获取token
  var tokenStr = window.localStorage.getItem('token');

  console.log('token', tokenStr)

  if (!tokenStr)
    return next('/login');

  next();

})

export default router